
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>地图展示</title>
    <style>
        body, #map-box, #show-map, #address-search {
            padding: 0 !important;
            margin: 0 !important;
        }

        #search-map{
            width: 1000px;
            height: 1000px;
            z-index: 999;
            position: fixed;
            left:-1000px ;
            top:-1000px ;
        }

        #map-box {
            position: relative;
            max-width: 100% !important;
            max-height: 100% !important;
            height: calc(100vh - 4px);
            width: 100vw;
        }

        #map-box #show-map {
            position: absolute;
            left: 0;
            top: 0;
            max-width: 100% !important;
            max-height: 100% !important;
            height: calc(100vh - 4px);
            width: 100vw;
        }

        #map-box #address-search {
            padding: 10px !important;
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            max-width: 500px;
            height: 90vh;
            max-height: 80%;
            background: #ffffff;
            z-index: 9999;
            border: 1px solid #dcdfe6;
            display: none;
        }

        #map-box #address-search input {
            width: calc(100% - 15px);
            padding: 7px 5px;
            background: #ffffff;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            outline: none;
        }

        #map-box #address-search span {
            position: absolute;
            font-size: 14px;
            top: 11px;
            right: 14px;
            color: #ff0000;
            cursor: pointer;
            line-height: 30px;
            padding: 0 5px;
        }


        #map-box #address-search ul {
            display: none;
            margin: 10px 0 0 0;
            padding: 0;
            height: calc(90vh - 85px);
            overflow-y: auto;
        }

        #map-box #address-search ul li {
            list-style-type: decimal;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            -o-text-overflow: ellipsis;
            border-bottom: 1px solid #dcdfe6;
            padding: 8px 5px;
            font-size: 13px;
            cursor: pointer;
        }

        #map-box #address-search ul li.address-item {
            cursor: pointer;
        }

        #map-box #address-search ul li:hover {
            background: #4875fd2e;
            color: #8c8c8c;
        }


        #map-box #center {
            display: inline-block;
            width: 24px;
            height: 24px;
            position: absolute;
            bottom: 10px;
            right: 10px;
            z-index: 1000;
            background-image: url("");
            background-position: center center;
            background-size: 24px;
            cursor: pointer;
        }


        #map-box #open-seach {
            display: inline-block;
            width: 24px;
            height: 24px;
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1000;
            background-image: url("");
            background-position: center center;
            background-size: 24px;
            cursor: pointer;
        }
    </style>
    <script charset="UTF-8" src="./components.js"></script>
</head>
<body>
<div id="map-box">
    <div id="search-map"></div>
    <div id="show-map"></div>
    <div id="address-search">
        <input id="keyword" placeholder="请输入地址">
        <span id="clera-search">取消搜索</span>
        <ul id="result-list"></ul>
    </div>
    <span id="open-seach" title="点击搜索"></span>
    <span id="center" title="返回中心点"></span>
</div>
</body>
<script>
    const {key, lng, lat, event} = getQueryParams()
    const zoom = 16;
    let Txmap, mapInstance,SearchInstance, marker, center, searchObject = null//地图实例
    let auto = false

    const ResultDome = document.getElementById('result-list')

    /**
     * 监听地址搜搜
     */
    document.getElementById('keyword').addEventListener('change', function (event) {
        let value = event.target.value
        if (value && value.length > 0) {
            searchObject.searchRectangle({keyword: value, bounds: SearchInstance.getBounds()})
                .then((result) => {
                    if (result.status === 0) {
                        randerSearch(result.data)
                    } else {
                        randerSearch([])
                    }
                })
                .catch(err => {
                    randerSearch([])
                    postMessage(400, err.message)
                })
        } else {
            randerSearch([])
        }
    })

    /**
     * 清空取消搜索
     */
    document.getElementById('clera-search').addEventListener('click', function () {
        ResultDome.innerHTML = ''
        ResultDome.style.display = 'none'
        document.getElementById('address-search').style.display = 'none'
    })

    function randerSearch(data) {
        if (data.length === 0) {
            ResultDome.innerHTML = ''
            ResultDome.style.display = 'none'
        } else {
            let html = ''
            for (let item of data) {
                html += `<li class="address-item" onclick="selectPoint(${item.location.lng},${item.location.lat})" data-lng="${item.location.lng}" data-lat="${item.location.lat}">${item.title} ${item.address}</li>`
            }
            ResultDome.innerHTML = html
            ResultDome.style.display = 'block'
        }
    }

    /**
     * 选择搜索地址
     * @param lng
     * @param lat
     */
    function selectPoint(lng, lat) {
        setMarker(lng, lat, true)
        ResultDome.innerHTML = ''
        ResultDome.style.display = 'none'
        document.getElementById('address-search').style.display = 'none'
    }


    function clearMarker() {
        if (marker) {
            marker.setMap(null)
            marker = null
        }
    }


    /**
     * 发送数据
     */
    function postMessage(code, msg, data) {
        let postData = {code, msg, event}
        if (typeof data !== 'undefined') {
            postData.data = data
        }
        window.parent.postMessage(JSON.stringify(postData), '*');
    }


    /**
     * 设置标记点
     * @param lngval
     * @param latval
     * @param sendinfo
     */
    function setMarker(lngval, latval, sendinfo) {
        center = new Txmap.LatLng(parseFloat(latval), parseFloat(lngval))
        if (mapInstance) {
            mapInstance.setCenter(center)

            //清除之前的点标记
            clearMarker()

            //重新创建点标记
            marker = new Txmap.MultiMarker({
                map: mapInstance,
                geometries: [{position: center}]
            })
        }
        if (sendinfo === true) {
            postMessage(200, '位置获取成功', {lng: lngval, lat: latval})
        }
        mapinit = true
    }


    function getIpLocation() {
        auto = true
        let IPLocation = new Txmap.service.IPLocation();
        IPLocation.locate().then(result => {
            if (result.status === 0 && result.result && result.result.location) {
                setMarker(result.result.location.lng, result.result.location.lat, true)
            } else {
                postMessage(400, '定位失败,请手动选择位置')
            }
        }).catch(err => {
            postMessage(400, err.message)
        })
    }


    function renderMap(TMap) {
        Txmap = TMap
    
        if (lng && lat) {
            mapInstance = new Txmap.Map(document.getElementById('show-map'), {
                rotation: 0,//设置地图旋转角度
                pitch: 0, //设置俯仰角度（0~45）
                center: new Txmap.LatLng(parseFloat(lat), parseFloat(lng)),//设置地图中心点坐标
                zoom: zoom,   //设置地图缩放级别
                viewMode: '2D'
            });
            setMarker(lng, lat)
        } else {
            mapInstance = new Txmap.Map(document.getElementById('show-map'), {
                rotation: 0,//设置地图旋转角度
                pitch: 0, //设置俯仰角度（0~45）
                zoom: zoom,   //设置地图缩放级别
                viewMode: '2D'
            });
        }


        setTimeout(()=>{
            SearchInstance = new Txmap.Map(document.getElementById('search-map'), {
                rotation: 0,//设置地图旋转角度
                pitch: 0, //设置俯仰角度（0~45）
                zoom: 4,   //设置地图缩放级别
                viewMode: '2D'
            });
        },500)

        /**
         * 地图加载完成事件
         */
        mapInstance.on("tilesloaded", () => {
            if (!(lng && lat)) {
                if (auto === false) {
                    getIpLocation()
                }
            }
        });

        //地图点击事件
        mapInstance.on("click", evt => {
            setMarker(evt.latLng.getLng(), evt.latLng.getLat(), true)
        })

        bindEvent()
    }


    /**
     * 绑定事件
     */
    function bindEvent() {
        searchObject = new Txmap.service.Search({pageSize: 30}); // 新建一个地点搜索类


        /**
         * 返回中心点
         */
        document.getElementById('center')?.addEventListener('click', function () {
            if (center && mapInstance) {
                mapInstance.setCenter(center)
                mapInstance.zoomTo(zoom);
            }
        })


        /**
         * 打开搜索
         */
        document.getElementById('open-seach')?.addEventListener('click', function () {
            document.getElementById('address-search').style.display = 'block'
        })
    }


    /**
     * 初始化地图
     */
    function init() {
        window.TMap = {
            "__load": function (onLoad) {
                onLoad({"key": key, "version": "1.6.6.6", "highQualityRender": false}, (new Date()).getTime());
                delete TMap.__load;
                Txmap = TMap
                setTimeout(() => renderMap(TMap), 200)
            }
        }

        //动态加载地图SDK
        const scriptElement = document.createElement('script')
        scriptElement.type = 'text/javascript'
        scriptElement.src = `//map.qq.com/api/gljs?v=1.exp&libraries=service&key=${key}`
        document.body.appendChild(scriptElement)
    }

    init()

</script>
</html>